import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:graphql_flutter/graphql_flutter.dart';
import 'package:labcloud_app/data/order.dart';
import 'package:labcloud_app/model/order_model.dart';
import 'package:labcloud_app/api/graphql/order_gql.dart';
import 'package:labcloud_app/widget/async_image.dart';

class OrderDetailPage extends StatefulWidget {
  const OrderDetailPage({super.key});

  @override
  _OrderDetailPageState createState() => _OrderDetailPageState();
}

class _OrderDetailPageState extends State<OrderDetailPage> {
  Order? currentOrder;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      final args = ModalRoute.of(context)?.settings.arguments;
      if (args != null && args is Order) {
        setState(() {
          currentOrder = args;
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('订单详情')),
      body: currentOrder == null
          ? const Center(child: Text('订单信息不存在'))
          : _buildOrderDetail(),
    );
  }

  Widget _buildOrderDetail() {
    final orderModel = context.read<OrderModel>();
    return SingleChildScrollView(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 订单状态卡片
          Card(
            margin: const EdgeInsets.all(10),
            child: Padding(
              padding: const EdgeInsets.all(15),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      const Text(
                        '订单状态',
                        style: TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      Container(
                        padding: const EdgeInsets.symmetric(
                          horizontal: 10,
                          vertical: 5,
                        ),
                        decoration: BoxDecoration(
                          color: orderModel.getStatusColor(
                            currentOrder?.status,
                          ),
                          borderRadius: BorderRadius.circular(15),
                        ),
                        child: Text(
                          orderModel.getStatusText(currentOrder?.status),
                          style: const TextStyle(
                            color: Colors.white,
                            fontSize: 12,
                          ),
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 10),
                  Text('订单编号: ${currentOrder?.id}'),
                  Text('创建时间: ${currentOrder?.createTime}'),
                  if (currentOrder?.payTime != null &&
                      currentOrder!.payTime!.isNotEmpty)
                    Text('支付时间: ${currentOrder?.payTime}'),
                ],
              ),
            ),
          ),

          // 收货信息卡片
          Card(
            margin: const EdgeInsets.all(10),
            child: Padding(
              padding: const EdgeInsets.all(15),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const Text(
                    '收货信息',
                    style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                  ),
                  const SizedBox(height: 10),
                  Text('收货人: ${currentOrder?.receiverName}'),
                  Text('联系电话: ${currentOrder?.receiverPhone}'),
                  Text('收货地址: ${currentOrder?.receiverAddress}'),
                ],
              ),
            ),
          ),

          // 商品信息卡片
          Card(
            margin: const EdgeInsets.all(10),
            child: Padding(
              padding: const EdgeInsets.all(15),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const Text(
                    '商品信息',
                    style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                  ),
                  const SizedBox(height: 10),
                  ...?currentOrder?.products?.map(
                    (product) => _buildProductItem(product),
                  ),
                ],
              ),
            ),
          ),

          // 订单金额卡片
          Card(
            margin: const EdgeInsets.all(10),
            child: Padding(
              padding: const EdgeInsets.all(15),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const Text(
                    '订单金额',
                    style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                  ),
                  const SizedBox(height: 10),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      const Text('商品总额'),
                      Text('¥${currentOrder?.totalPrice}'),
                    ],
                  ),
                  const SizedBox(height: 5),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      const Text('实付金额'),
                      Text(
                        '¥${currentOrder?.realPrice}',
                        style: const TextStyle(
                          color: Colors.red,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),

          // 底部操作按钮
          Container(
            padding: const EdgeInsets.all(10),
            decoration: const BoxDecoration(
              color: Colors.white,
              boxShadow: [
                BoxShadow(
                  color: Colors.grey,
                  offset: Offset(0, -1),
                  blurRadius: 2,
                ),
              ],
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                // 根据订单状态显示不同的按钮组合
                if (currentOrder?.status == 'non_pay') ...[
                  // 未支付订单：显示取消订单和立即支付按钮
                  ElevatedButton(
                    onPressed: () => _cancelOrder(
                      orderModel,
                      currentOrder!.id!,
                    ),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.grey,
                      foregroundColor: Colors.white,
                    ),
                    child: const Text('取消订单'),
                  ),
                  const SizedBox(width: 10),
                  ElevatedButton(
                    onPressed: () => _payOrder(
                      orderModel,
                      currentOrder!.id! ,
                    ),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.blue,
                      foregroundColor: Colors.white,
                    ),
                    child: const Text('立即支付'),
                  ),
                ] else if (currentOrder?.status == 'undelivered') ...[
                  // 未配送订单：显示模拟送达和取消订单按钮
                  ElevatedButton(
                    onPressed: () => _cancelOrder(
                      orderModel,
                      currentOrder!.id!,
                    ),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.grey,
                      foregroundColor: Colors.white,
                    ),
                    child: const Text('取消订单'),
                  ),
                  const SizedBox(width: 10),
                  ElevatedButton(
                    onPressed: () => _deliverOrder(
                      orderModel,
                      currentOrder!.id!,
                    ),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.blue,
                      foregroundColor: Colors.white,
                    ),
                    child: const Text('模拟送达'),
                  ),
                ] else if (currentOrder?.status == 'unconfirmed') ...[
                  // 未确认订单：显示确认收货和申请售后按钮
                  ElevatedButton(
                    onPressed: () => _applyAfterSales(
                      orderModel,
                      currentOrder!.id!,
                    ),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.grey,
                      foregroundColor: Colors.white,
                    ),
                    child: const Text('申请售后'),
                  ),
                  const SizedBox(width: 10),
                  ElevatedButton(
                    onPressed: () => _confirmReceipt(
                      orderModel,
                      currentOrder!.id!,
                    ),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.blue,
                      foregroundColor: Colors.white,
                    ),
                    child: const Text('确认收货'),
                  ),
                ],
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildProductItem(Product product) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 10),
      child: Row(
        children: [
          ClipRRect(
            borderRadius: BorderRadius.circular(5),
            child: SizedBox(
              width: 60,
              height: 60,
              child: AsyncImageWidget(
                imageUrl: product.coverAddr ?? '',
                fit: BoxFit.cover,
              ),
            ),
          ),
          const SizedBox(width: 10),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  product.title ?? '',
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                  style: const TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const SizedBox(height: 5),
                // 商品价格需要从订单总价和数量计算得出
                Text('¥${_calculateProductPrice(product)}'),
                Text('数量: ${product.quantity}'),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // 根据订单总价和商品数量计算单价
  String _calculateProductPrice(Product product) {
    try {
      final orderModel = context.read<OrderModel>();
      if (currentOrder?.totalPrice != null && product.quantity != null) {
        final totalPrice = double.tryParse(currentOrder!.totalPrice!);
        if (totalPrice != null && totalPrice > 0 && product.quantity! > 0) {
          final unitPrice = totalPrice / product.quantity!;
          return unitPrice.toStringAsFixed(2);
        }
      }
    } catch (e) {
      // 计算出错时返回默认值
    }
    return '0.00';
  }

  Future<void> _cancelOrder(OrderModel orderModel, String orderId) async {
    try {
      final client = GraphQLProvider.of(context).value;

      final result = await client.mutate(
        MutationOptions(
          document: gql(OrderGQL.fetchOrderCancel),
          variables: {'orderId': orderId},
        ),
      );

      if (result.hasException) {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('取消订单失败: ${result.exception.toString()}')),
          );
        }
        return;
      }

      if (mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(const SnackBar(content: Text('订单已取消')));
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(SnackBar(content: Text('取消订单异常: $e')));
      }
    }
  }

  Future<void> _deliverOrder(OrderModel orderModel, String orderId) async {
    try {
      final client = GraphQLProvider.of(context).value;

      final result = await client.mutate(
        MutationOptions(
          document: gql(OrderGQL.fetchOrderDelivered),
          variables: {'orderId': orderId},
        ),
      );

      if (result.hasException) {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('模拟送达失败: ${result.exception.toString()}')),
          );
        }
        return;
      }

      if (mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(const SnackBar(content: Text('订单已送达')));
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(SnackBar(content: Text('模拟送达异常: $e')));
      }
    }
  }

  Future<void> _confirmReceipt(OrderModel orderModel, String orderId) async {
    try {
      final client = GraphQLProvider.of(context).value;

      final result = await client.mutate(
        MutationOptions(
          document: gql(OrderGQL.fetchOrderConfirm),
          variables: {'orderId': orderId},
        ),
      );

      if (result.hasException) {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('确认收货失败: ${result.exception.toString()}')),
          );
        }
        return;
      }

      if (mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(const SnackBar(content: Text('确认收货成功')));
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(SnackBar(content: Text('确认收货异常: $e')));
      }
    }
  }

  Future<void> _applyAfterSales(OrderModel orderModel, String orderId) async {
    if (mounted) {
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(const SnackBar(content: Text('申请售后功能待实现')));
    }
  }

  // 显示支付密码验证对话框
  void _showPaymentPasswordDialog({
    required BuildContext context,
    required void Function(String password) onSuccess,
    required VoidCallback onCancel,
  }) {
    final TextEditingController passwordController = TextEditingController();

    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('输入支付密码'),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              const Text('请输入6位数字支付密码'),
              const SizedBox(height: 15),
              TextField(
                controller: passwordController,
                keyboardType: TextInputType.number,
                obscureText: true,
                maxLength: 6,
                decoration: const InputDecoration(
                  hintText: '请输入支付密码',
                  border: OutlineInputBorder(),
                ),
              ),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () {
                onCancel();
              },
              child: const Text('取消'),
            ),
            TextButton(
              onPressed: () {
                final password = passwordController.text;

                if (password.isEmpty) {
                  ScaffoldMessenger.of(
                    context,
                  ).showSnackBar(const SnackBar(content: Text('请输入支付密码')));
                  return;
                }

                if (password.length != 6 ||
                    !RegExp(r'^\d{6}$').hasMatch(password)) {
                  ScaffoldMessenger.of(
                    context,
                  ).showSnackBar(const SnackBar(content: Text('支付密码必须为6位数字')));
                  return;
                }

                onSuccess(password);
              },
              child: const Text('确定'),
            ),
          ],
        );
      },
    );
  }

  Future<void> _payOrder(OrderModel orderModel, String orderId) async {
    // 显示支付密码验证对话框
    _showPaymentPasswordDialog(
      context: context,
      onSuccess: (password) {
        Navigator.pop(context); // 关闭支付密码对话框
        _executePayOrder(orderModel, orderId, password);
      },
      onCancel: () {
        Navigator.pop(context); // 关闭支付密码对话框
      },
    );
  }

  Future<void> _executePayOrder(
    OrderModel orderModel,
    String orderId,
    String payPassword,
  ) async {
    try {
      final client = GraphQLProvider.of(context).value;

      final result = await client.mutate(
        MutationOptions(
          document: gql(OrderGQL.fetchOrderPay),
          variables: {'orderId': orderId, 'payPassword': payPassword},
        ),
      );

      if (result.hasException) {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('支付失败: ${result.exception.toString()}')),
          );
        }
        return;
      }

      if (mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(const SnackBar(content: Text('支付成功')));

        // 可以导航到支付成功页面
        // Navigator.of(context).pushNamed('/payment_success');
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(SnackBar(content: Text('支付异常: $e')));
      }
    }
  }
}
